package com.jkoss.wine.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jkoss.wine.system.entity.MerchantEmployees;
import com.jkoss.wine.system.entity.MerchantEmployeesRole;
import com.jkoss.wine.system.entity.Role;
import com.jkoss.wine.system.mapper.MerchantEmployeesMapper;
import com.jkoss.wine.system.mapper.MerchantEmployeesRoleMapper;
import com.jkoss.wine.system.mapper.RoleMapper;
import com.jkoss.wine.system.service.IRoleService;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author chair
 * @since 2018-09-20
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
	@Autowired
	private MerchantEmployeesRoleMapper merchantEmployeesRoleMapper;

	@Autowired
	private MerchantEmployeesMapper merchantEmployeesMapper;

	@Override
	public Page selectVoByPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByPage(page, wrapper));
		return page;
	}

	@Override
	public Set selectChildren(String id) {
		// 查询用户拥有多少角色
		Wrapper mrWrapper = Condition.create().eq("meid", id);
		List<MerchantEmployeesRole> employeesRoles = merchantEmployeesRoleMapper.selectList(mrWrapper);
		// 去除重复数据
		Set set = new HashSet<>();
		for (MerchantEmployeesRole merchantEmployeesRole : employeesRoles) {
			set.add(merchantEmployeesRole.getRid());
		}
		// 查询所有角色id的子级id
		Wrapper wrapper = Condition.create().in("id", set);
		List<String> list = baseMapper.selectChildren(wrapper);
		// 去除重复
		Set set2 = new HashSet<>();
		for (String str : list) {
			set2.addAll(Arrays.asList(str.split(",")));
		}

		// 查询角色下的用户
		Wrapper mrWrapper2 = Condition.create().in("rid", set2);
		List<MerchantEmployeesRole> employeesRoles2 = merchantEmployeesRoleMapper.selectList(mrWrapper2);
		Set set3 = new HashSet<>();
		for (MerchantEmployeesRole merchantEmployeesRole : employeesRoles2) {
			set3.add(merchantEmployeesRole.getMeid());
		}
		Set set4 = new HashSet<>();
		if (set.contains("747576fb21524f29885bcaedf6bf6bdb")) {
			set4 = set3;
		} else {
			// 查询用户是否在部门下
			MerchantEmployees employees = merchantEmployeesMapper.selectById(id);
			Wrapper meWrapper = Condition.create().in("employee_id", set3).eq("dmid", employees.getDmid());
			List<MerchantEmployees> employees2 = merchantEmployeesMapper.selectList(meWrapper);
			for (MerchantEmployees merchantEmployees : employees2) {
				set4.add(merchantEmployees.getEmployeeId());
			}
		}

		return set4;
	}
}
